﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using RED_NET_Core.BLL;
using RED_NET_Core.Entity;
using RED_NET_Core.Utilty;

namespace RED_NET.ContentPage.User
{
    public partial class UpdateInfo : System.Web.UI.Page
    {
        private static int uId=-1;
        private static int visitId;
        protected void Init()
        {
            Session["PageName"] = "UpdateInfo";
            div1.Visible = true;
            div2.Visible = false;
            div3.Visible = false;
            success.Visible = false;
          
            if (Session["USER_ID"] != null)
                        uId = (int)Session["USER_ID"];
            else
              Response.Redirect("~/ContentPage/Error/PageError.aspx");
            if (Request.QueryString["VISIT_ID"] != null)
                visitId = Int32.Parse(Request.QueryString["VISIT_ID"]);
            else
              Response.Redirect("~/ContentPage/Error/PageError.aspx");
           
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            Init();
        }
        protected void LinkButton_update_avatar_Click(object sender, EventArgs e)
        {
            div1.Visible = false;
            div2.Visible = true;
            div3.Visible = false;
            success.Visible = false;

        }
        protected void LinkButton_update_password_Click(object sender, EventArgs e)
        {
            div1.Visible = false;
            div2.Visible = false;
            div3.Visible = true;
            Label_errorOld.Visible = false;
            Label_errorNew.Visible = false;
            Label_errorNewTwo.Visible = false;
            success.Visible = false;
            TextBox_NewPass.Text = "";
            TextBox_NewPassTwo.Text = "";
            TextBox_OldPass.Text = "";
        }
       
        protected void LinkButton_return_Click(object sender, EventArgs e)
        {
            Init();

        }
        protected void LinkButton_Update2_Click(object sender, EventArgs e)
        {
            LoginBLL _login = new LoginBLL();
            int flag=1;
            string OldPass, NewPass, NewPassTwo;
            OldPass = TextBox_OldPass.Text;
            if (_login.IsValidUser(uId, OldPass) == false)
            {
                Label_errorOld.Text = "密码错误！";
                Label_errorOld.Visible = true;
                flag = 0;
            }
            NewPass = TextBox_NewPass.Text;
            ReturnValue rt = Safety.JudgePass(NewPass,6,20);
            if (rt.value != 0)
            {
                Label_errorNew.Text = rt.error;
                Label_errorNew.Visible = true;
                flag = 0;

            }
            NewPassTwo = TextBox_NewPassTwo.Text;
            rt = Safety.JudgePass(NewPassTwo,6,20);
            if (rt.value != 0)
            {
                Label_errorNewTwo.Text = rt.error;
                Label_errorNewTwo.Visible = true;
                flag = 0;

            }
            if (NewPass != NewPassTwo)
            {
                Label_errorNewTwo.Text = "密码不相等！";
                Label_errorNewTwo.Visible = true;
                flag = 0;
            }
            if (flag == 1)
            {
                try
                {
                    UserInfoBLL.UpdateMyPassword(uId,NewPass);
                }
                catch (Exception ex)
                {
                    Response.Redirect("~/ContentPage/Error/PageError.aspx");
                }
                div3.Visible = false;
                success.Visible = true;
            }
            else
            {

            }
         

        }
        protected void LinkButton_Update1_Click(object sender, EventArgs e)
        {
            bool fileOK = false;
            string _avatarUrl = "~\\Image_Css\\avatar\\";
            string path = Server.MapPath("~/Image_Css/avatar/");
            string fileExtension;
            if (FileUpload_update_avatar.HasFile)
            {
                 fileExtension = System.IO.Path.GetExtension(FileUpload_update_avatar.FileName).ToLower();
                String[] allowedExtensions = { ".gif", ".png", ".bmp", ".jpg" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                        break;
                    }
                }


            }
            else
            {
                Label_avatar_error.Text = "请选择头像的图片！";
                Label_avatar_error.Visible = true;
                return;
            }
            if (fileOK)
            {
                _avatarUrl+=uId.ToString()+fileExtension;
                path += uId.ToString() + fileExtension;
                try
                {
                    FileUpload_update_avatar.SaveAs(path);
                   UserInfoBLL.UpdateMyAvatar( uId, _avatarUrl);
                   div2.Visible = false;
                   success.Visible = true;
                }
                catch (Exception ex)
                {
                    Label_avatar_error.Text = "上传失败，请稍候再尝试！";
                } 

            }
            else
            {
                Label_avatar_error.Text = "请上传图片文件！";
                Label_avatar_error.Visible = true;
                return;
            }

       


        }
        #region[图片压缩函数]

        /// <summary>
        /// 可多次利用，增大缩小上传图片函数
        /// </summary>
        /// <param name="upImage">上传控件的ID值</param>
        /// <param name="savePath">图片保存的相对路径</param>
        /// <param name="toHeight">图片最大高度</param>
        /// <param name="toWidth">图片最大宽度</param>
        /// <returns></returns>
        public string MakeBigOrSmallImage(FileUpload upImage, String savePath, int toHeight, int toWidth)
        {
            bool IsChange = false;
            String ttFileName = "";//缩略图文件名
            String tFileName = "";//原始文件名
            String FileName = "";//没有扩展名的文件名
            if (upImage.PostedFile != null)
            {
                HttpPostedFile myImageFile = upImage.PostedFile;
                FileName = System.IO.Path.GetFileNameWithoutExtension(myImageFile.FileName);
                int tFileLen = myImageFile.ContentLength;
                if (tFileLen == 0) return "没有选择上传图片";
                String extension = System.IO.Path.GetExtension(myImageFile.FileName).ToLower();
                if (extension != ".jpg" && extension != ".jpge" && extension != ".png" && extension != ".bmp")
                    return "上传图片格式错误";
                byte[] myData = new byte[tFileLen];
                myImageFile.InputStream.Read(myData, 0, tFileLen);
                //检查当前文件名是否已经存在,若存在，在文件名末尾加1、2、3。。
                tFileName = System.IO.Path.GetFileName(myImageFile.FileName);
                int fileNum = 0;
                while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName)))
                {
                    fileNum++;
                    tFileName = FileName +
                        fileNum.ToString() + extension;
                }
                //保存图片
                System.IO.FileStream newFile = new System.IO.FileStream(
                    System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName),
                    System.IO.FileMode.Create, System.IO.FileAccess.Write);
                newFile.Write(myData, 0, tFileLen);
                newFile.Close();
                //如果图片长宽有任意一个比规定的大，那么压缩图
                try
                {
                    using (System.Drawing.Image sourceImage =
                       System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName)))
                    {
                        //原图高度
                        int oldHeight = sourceImage.Height;
                        int oldWidth = sourceImage.Width;
                        int nowHeight;
                        int nowWidth;
                        if (oldHeight > toHeight || oldWidth > toWidth)
                        {
                            if ((decimal)oldHeight / oldWidth <= (decimal)toHeight / toWidth)
                            {
                                nowHeight = toHeight;
                                nowWidth = toHeight * oldWidth / oldHeight;
                            }
                            else
                            {
                                nowWidth = toWidth;
                                nowHeight = toWidth * oldHeight / oldWidth;
                            }
                            //存好缩略图存放的绝对物理地址
                            ttFileName = "t" + FileName + extension; //小图片名前加个t，防止操作过程因覆盖原图导致程序错误
                            int tfileNum = 0;
                            while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(savePath + ttFileName)))
                            {
                                tfileNum++;
                                ttFileName = "t" + FileName + tfileNum.ToString() + extension;
                            }
                            String smallImageSavePath =
                                System.Web.HttpContext.Current.Server.MapPath(savePath + ttFileName);
                            //以等比例压缩绘制缩略图
                            using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(nowWidth, nowHeight))
                            {
                                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                                {
                                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                    g.Clear(System.Drawing.Color.Black);
                                    g.DrawImage(sourceImage, new System.Drawing.Rectangle(0, 0, nowWidth, nowHeight),
                                        new System.Drawing.Rectangle(0, 0, oldWidth, oldHeight),
                                        System.Drawing.GraphicsUnit.Pixel);
                                    bitmap.Save(smallImageSavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                            }
                            IsChange = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //压缩过程出错也视为有压缩，删除大图
                    IsChange = true;
                    throw ex;
                }
                //如果图片有压缩，那么删除大图
                if (IsChange) System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(savePath + tFileName));
            }
            return ttFileName;
        }

        #endregion

    }
}
